package com.example.controller;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.example.bean.User;
import com.example.mapper.UserMapper;
import com.example.util.JwtConfig;
import com.example.util.Ret;

@RestController
@RequestMapping("/")
public class IndexController {
	
	@Autowired
    private UserMapper userMapper;
	
	public static JwtConfig JwtConfig = new JwtConfig();
	
	/**
	 * 登录
	 * 
	 * @author: zhangwei
	 * @date: 2021年1月22日
	 */
	@RequestMapping("/login")
    public Ret login(String account, String password){
		try {
			User user = userMapper.selectUserByAccount(account);
	        if (user==null || !password.equals(user.getPassword())) {
	            return Ret.fail("msg","登录失败，密码或用户名错误！");
	        }
	        String token = JwtConfig.createToken(user.getAccount());
	        Cookie cookie=new Cookie("token", token);
	        getResponse().addCookie(cookie);
	        return Ret.ok("token", token).set("account", account);
		} catch (Exception e) {
			e.printStackTrace();
            return Ret.fail("msg","登录失败，出现未知错误，请刷新后重试！");
		}
    }
    
    private HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
    }
}







